package com.kstech.test.padxmledit;

import android.app.Fragment;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.kstech.test.padxmledit.domain.RealTimeSet;
import com.kstech.test.padxmledit.domain.DTC;
import com.kstech.test.padxmledit.domain.DataSet;
import com.kstech.test.padxmledit.domain.Device;
import com.kstech.test.padxmledit.domain.Images;
import com.kstech.test.padxmledit.domain.J1939;
import com.kstech.test.padxmledit.domain.Msg;
import com.kstech.test.padxmledit.domain.Msgs;
import com.kstech.test.padxmledit.domain.PG;
import com.kstech.test.padxmledit.domain.QCItem;
import com.kstech.test.padxmledit.domain.RealTimeSet;
import com.kstech.test.padxmledit.domain.SP;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

/**
 * Created by lenovo on 2016/9/7.
 */
public class ListFragMent extends Fragment {
    private DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    private DocumentBuilder builder;
    private Document document = null;
    private MyAdapter adapter;
    private ListEditFragment f;
    private LinkedList<SP> pSPList;
    private LinkedList<PG> pgList;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.listfragment,null);
        ListView lv = (ListView) view.findViewById(R.id.pad_list);
        TextView tv = (TextView) view.findViewById(R.id.tv_devices);
        xmlParse();
        adapter = new MyAdapter();
        lv.setAdapter(adapter);
        f = (ListEditFragment) getFragmentManager().findFragmentByTag("list_edit");
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if(!Globals.list_edit.contains(Globals.QClist.get(i))){
                    Globals.list_edit.add(Globals.QClist.get(i));
                    f.handler.sendEmptyMessage(0);
                }
            }
        });
        tv.setText(Globals.device.toString());
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.i(">>>>>>","list fragment update");
        adapter.notifyDataSetChanged();
    }

    public void xmlParse() {

        try {
            String src = "/storage/sdcard1/devices.xml";
            Log.i("kstech", "---路径---" + src);
            File fileName = new File(src);
            Log.i("kstech", "---fileName---" + fileName.getPath());
            builder = factory.newDocumentBuilder();
            document = builder.parse(fileName);
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // 1.获得文档根元素对对象;
        Element root = document.getDocumentElement();
        //填充设备基本信息
        Globals.device.setID(root.getAttribute("Id"));
        Globals.device.setName(root.getAttribute("Name"));
        Globals.device.setDevBornDate(root.getAttribute("DevBornDate"));
        Globals.device.setDevDieDate(root.getAttribute("DevDieDate"));
        Globals.device.setDevStatus(root.getAttribute("DevStatus"));
        // 获得文档根元素下一级子元素所有元素;
        NodeList nodeList = root.getChildNodes();
        System.out.println(root.getNodeName());
        for (int i = 0; i < nodeList.getLength(); i++) {
            /**
             * Resource标签解析
             */
            if ("Resource".equals(nodeList.item(i).getNodeName())) {
                Node resouce = nodeList.item(i);
                NodeList Resources = resouce.getChildNodes();
                LinkedList<Msg> msgLinkedList = new LinkedList<>();
                LinkedList<Images> imgLinkedList = new LinkedList<>();
                for(int r=0;r<Resources.getLength();r++){
                    //Log.i("hahah",Resources.item(r).getNodeName());
                    if("MsgSet".equals(Resources.item(r).getNodeName())){
                        Node MsgSet = Resources.item(r);
                        NodeList msgList = MsgSet.getChildNodes();
                        for(int ms=0;ms<msgList.getLength();ms++){
                            if("Msg".equals(msgList.item(ms).getNodeName())){
                                NamedNodeMap map = msgList.item(ms).getAttributes();
                                String ID = map.getNamedItem("Id").getNodeValue();
                                String RefName = map.getNamedItem("RefName").getNodeValue();
                                String Content = map.getNamedItem("Content").getNodeValue();
                                Msg msg = new Msg(ID,RefName,Content);
                                msgLinkedList.add(msg);
                                Log.i("hahah", ">>>>>>>>>id:" + ID + "name:" + RefName+Content+msgLinkedList.size());
                            }
                        }
                    }
                    if("ImageSet".equals(Resources.item(r).getNodeName())){
                        Node MsgSet = Resources.item(r);
                        NodeList msgList = MsgSet.getChildNodes();
                        for(int ms=0;ms<msgList.getLength();ms++){
                            if("Image".equals(msgList.item(ms).getNodeName())){
                                NamedNodeMap map = msgList.item(ms).getAttributes();
                                String ID = map.getNamedItem("Id").getNodeValue();
                                String RefName = map.getNamedItem("RefName").getNodeValue();
                                String Content = map.getNamedItem("Content").getNodeValue();
                                Images images = new Images(ID,RefName,Content);
                                if(!imgLinkedList.contains(images)){
                                    imgLinkedList.add(images);
                                }
                                Log.i("hahah", ">>>>>>>>>id:" + ID + "name:" + RefName+Content+"---"+imgLinkedList.size());
                            }
                        }
                    }

                }
                //吧解析完成的ImagSet,MsgSet放入global中的Devices
                Globals.device.setImageSet(imgLinkedList);
                Globals.device.setMsgSet(msgLinkedList);
            }

            /**
             * DataSet 开始解析----------------------------------------------------------------------------------
             */
            if ("DataSet".equals(nodeList.item(i).getNodeName())) {
                Node dataSet = nodeList.item(i);
                System.out.println(dataSet.getNodeName());
                NodeList DSItems = dataSet.getChildNodes();
                // 循环获取DSItem信息
                for (int j = 0; j < DSItems.getLength(); j++) {
                    if ("DSItem".equals(DSItems.item(j).getNodeName())) {
                        //读取DSItem每个属性，并填充到类中
                        Node item = DSItems.item(j);
                        NamedNodeMap map = item.getAttributes();
                        //name 名字
                        Node Name = map.getNamedItem("Name");
                        String name = Name.getNodeValue();
                        //datatype 数据类型
                        Node DataType = map.getNamedItem("DataType");
                        String type = DataType.getNodeValue();

                        DataSet data = new DataSet(type);
                        data.setName(name);
                        //unit 单位
                        Node Unit = map.getNamedItem("Unit");
                        if (Unit != null) {
                            data.setUnit(Unit.getNodeValue());
                        }
                        //linkto 指向相关dsitem 遍历获取相关实例下标
                        Node LinkTo = map.getNamedItem("LinkTo");
                        if (LinkTo != null) {
                            Object[] datas = Globals.list.toArray();
                            for (Object ds : datas) {
                                DataSet d = (DataSet) ds;
                                if (LinkTo.getNodeValue().equals(d.getName())) {
                                    data.setLinkTo(Globals.list.indexOf(d));
                                }
                            }
                        }
                        //declen 精确到小数点后位数
                        Node DecLen = map.getNamedItem("DecLen");
                        if (DecLen != null) {
                            data.setDeclen(Integer.parseInt(DecLen.getNodeValue()));
                        }
                        //Value Value之的获取
                        Node Value = map.getNamedItem("Value");
                        if (Value != null) {
                            data.setValues(Float.parseFloat(Value.getNodeValue()));
                        }
                        //indexby 指向相关dsitem 遍历获取相关实例下标
                        Node IndexBy = map.getNamedItem("IndexBy");
                        if (IndexBy != null) {
                            Object[] datas = Globals.list.toArray();
                            for (Object ds : datas) {
                                DataSet d = (DataSet) ds;
                                if (IndexBy.getNodeValue().equals(d.getName())) {
                                    data.setIndexBy(Globals.list.indexOf(d));
                                }
                            }
                        }
                        //rows 包含的集合数目
                        Node Rows = map.getNamedItem("Rows");
                        if (Rows != null) {
                            data.setRows(Integer.parseInt(Rows.getNodeValue()));
                        }
                        Globals.list.add(data);
                        //Globals.list.add(data);
                        System.out.println(data);
                        System.out
                                .println("----------------------------------------------------");
                    }
                }
                Globals.device.setDSItems(Globals.list);
            }
            /**
             * dataSet 解析结束-------------------------------------------------------------------------------------------------------
             */

            /**
             * j1939解析
             */
            if("J1939".equals(nodeList.item(i).getNodeName())){
                Element eJ1939 = (Element) nodeList.item(i);
                J1939 mj1939 = new J1939();
                mj1939.setNodeAddr(eJ1939.getAttribute("NodeAddr"));
                mj1939.setCycle(eJ1939.getAttribute("Cycle"));
                mj1939.setTaskPrio(eJ1939.getAttribute("TaskPrio"));
                //Log.i("j1939",">>>>><<<<<"+eJ1939.getAttribute("NodeAddr"));
                Globals.device.setmJ1939(mj1939);
                NodeList J1939s = eJ1939.getChildNodes();
                pgList = new LinkedList<>(); //声明一个list 粗存PG
                for(int j=0;j<J1939s.getLength();j++){
                   // Log.i("j1939",">>>>><<<<<"+J1939s.item(j).getNodeName());
                    if("PG".equals(J1939s.item(j).getNodeName())) {
                        Element mPg = (Element) J1939s.item(j);//获得单个PG
                        PG pg = new PG();
                        pg.setType(mPg.getAttribute("Type"));
                        pg.setDir(mPg.getAttribute("Dir"));
                        pg.setPrio(mPg.getAttribute("Prio"));
                        pg.setLen(mPg.getAttribute("Len"));
                        pg.setRate(mPg.getAttribute("Rate"));
                        pg.setPGN(mPg.getAttribute("PGN"));
                        pg.setSA(mPg.getAttribute("SA"));
                        pg.setReq(mPg.getAttribute("Req"));
                        pg.setReqCyc(mPg.getAttribute("ReqCyc"));
                        //Log.i("j1939",">>>>><<<<<"+mPg.getAttribute("PGN"));
                        NodeList spList = mPg.getChildNodes();// 遍历PG内部SP
                        pSPList = new LinkedList<>(); //设置一个list去储存sp，并放到pg中
                        for(int p=0;p<spList.getLength();p++){
                            if("SP".equals(spList.item(p).getNodeName())){
                                Node mSP = spList.item(p);
                                SP sp = new SP();
                                NamedNodeMap map = mSP.getAttributes();
                                sp.setType(map.getNamedItem("Type").getNodeValue());
                                sp.setBits(map.getNamedItem("Bits").getNodeValue());
                                sp.setBytes(map.getNamedItem("Bytes").getNodeValue());
                                sp.setOff(map.getNamedItem("Off").getNodeValue());
                                sp.setRef(map.getNamedItem("Ref").getNodeValue());
                                sp.setRes(map.getNamedItem("Res").getNodeValue());
                                sp.setSBit(map.getNamedItem("SBit").getNodeValue());
                                sp.setSByte(map.getNamedItem("SByte").getNodeValue());
                                if(map.getNamedItem("SPN")!=null){
                                    sp.setSPN(map.getNamedItem("SPN").getNodeValue());
                                }
                                if(mSP.hasChildNodes()){
                                    LinkedList<DTC> dtcLinkedList = new LinkedList();
                                    NodeList dtcList = mSP.getChildNodes();
                                    for(int d=0;d<dtcList.getLength();d++){
                                        if("DTC".equals(dtcList.item(d).getNodeName())){
                                            Node nodeDTC = dtcList.item(d);
                                            DTC mDTC = new DTC();
                                            NamedNodeMap dtcMap = nodeDTC.getAttributes();
                                            mDTC.setFMI(dtcMap.getNamedItem("FMI").getNodeValue());
                                            mDTC.setMsgId(dtcMap.getNamedItem("MsgId").getNodeValue());
                                            mDTC.setIcon(dtcMap.getNamedItem("Icon").getNodeValue());
                                            Log.i("DTC",dtcMap.getNamedItem("MsgId").getNodeValue());
                                            dtcLinkedList.add(mDTC);
                                        }
                                    }
                                    sp.setDTCList(dtcLinkedList);
                                }
                                pSPList.add(sp);
                            }
                        }
                        pg.setPGList(pSPList);
                        pgList.add(pg);
                    }
                }
                Globals.device.getmJ1939().setPGList(pgList);
                Log.i("j1939","<<<>>>><<<<>>>"+Globals.device.getmJ1939().getPGList().size()+Globals.device.getmJ1939().getPGList().getFirst().getPGN());
            }
            /**
             * J1939解析结束
             */
            /**
             * QCSET解析 ----------------------------------------------------------------
             */
                if("QCSet".equals(nodeList.item(i).getNodeName())){
                    Log.i("QCItem",">>>>>>>>开始QCS ET解析<<<<<<<<<");
                    Node QCSet = nodeList.item(i);
                    NodeList qcItems = QCSet.getChildNodes();
                    LinkedList<QCItem> qciList = new LinkedList<>();
                    for(int q=0;q<qcItems.getLength();q++){
                        if("QCItem".equals(qcItems.item(q).getNodeName())){
                            Element qcItem = (Element) qcItems.item(q);
                            Log.i("QCItem",">>>>>>>>"+qcItem.getAttribute("Name")+"<<<<<<<<<");
                            QCItem mQCItem = new QCItem();
                            mQCItem.setID(qcItem.getAttribute("Id"));
                            mQCItem.setName(qcItem.getAttribute("Name"));
                            mQCItem.setRequire(qcItem.getAttribute("Require"));
                            mQCItem.setQCTimes(qcItem.getAttribute("QCTimes"));
                            mQCItem.setReadyTimeout(qcItem.getAttribute("ReadyTimeout"));
                            mQCItem.setQCTimeout(qcItem.getAttribute("QCTimeout"));
                            NodeList qcList = qcItem.getChildNodes();
                            Msgs m = new Msgs();
                            LinkedList<QCItem.QCParam> qqList = new LinkedList<>();
                            LinkedList<QCItem.ENVParam> envList = new LinkedList<>();
                            for(int ql=0;ql<qcList.getLength();ql++){
                                if("Msgs".equals(qcList.item(ql).getNodeName())){
                                    Log.i("QCItem",">>>>>>>>"+qcList.item(ql).getNodeName()+"<<<<<<<<<");
                                    Element mMsgs = (Element) qcList.item(ql);
                                    m.setReadyMsg(mMsgs.getAttribute("ReadyMsg"));
                                    m.setNotReadyMsg(mMsgs.getAttribute("NotReadyMsg"));
                                    m.setAbortMsg(mMsgs.getAttribute("AbortMsg"));
                                    m.setOkMsg(mMsgs.getAttribute("OkMsg"));
                                    Log.i("QCItem",">>>>>>>>"+mMsgs.getAttribute("ReadyMsg")+"<<<<<<<<<");
                                    NodeList msgList = mMsgs.getChildNodes();
                                    LinkedList<Msgs.QCErr> errLinkedList = new LinkedList<>();
                                    LinkedList<Msgs.QCProgress> progresLinkedList = new LinkedList<>();
                                    for(int ms=0;ms<msgList.getLength();ms++){
                                        if("QCProgressMsg".equals(msgList.item(ms).getNodeName())){
                                            Log.i("QCItem",">>>>>>>>"+msgList.item(ms).getNodeName()+"<<<<<<<<<");
                                            Node QCProgressMsg = msgList.item(ms);
                                            NodeList qcProgressMsgList = QCProgressMsg.getChildNodes();
                                            for(int qpm=0;qpm<qcProgressMsgList.getLength();qpm++){
                                                if("QCProgress".equals(qcProgressMsgList.item(qpm).getNodeName())){
                                                    Node qcProM = qcProgressMsgList.item(qpm);
                                                    Msgs.QCProgress mq = new Msgs.QCProgress();
                                                    NamedNodeMap map = qcProM.getAttributes();
                                                    mq.Code = map.getNamedItem("Code").getNodeValue();
                                                    mq.Msg = map.getNamedItem("Msg").getNodeValue();
                                                    Log.i("QCItem",">>>>>MSG>>>"+ mq.Msg+"<<<<<<<<<");
                                                    progresLinkedList.add(mq);
                                                }
                                            }
                                        }
                                        if("QCErrMsg".equals(msgList.item(ms).getNodeName())){
                                            Log.i("QCItem",">>>>>>>>"+msgList.item(ms).getNodeName()+"<<<<<<<<<");
                                            Node QCProgressMsg = msgList.item(ms);
                                            NodeList qcProgressMsgList = QCProgressMsg.getChildNodes();
                                            for(int qpm=0;qpm<qcProgressMsgList.getLength();qpm++){
                                                if("QCErr".equals(qcProgressMsgList.item(qpm).getNodeName())){
                                                    Node qcProM = qcProgressMsgList.item(qpm);
                                                    Msgs.QCErr mq = new Msgs.QCErr();
                                                    NamedNodeMap map = qcProM.getAttributes();
                                                    mq.Code = map.getNamedItem("Code").getNodeValue();
                                                    mq.Msg = map.getNamedItem("Msg").getNodeValue();
                                                    errLinkedList.add(mq);
                                                }
                                            }
                                        }
                                    }
                                    m.setQCProgressMsg(progresLinkedList);
                                    m.setQCErrMsg(errLinkedList);
                                }
                                //------------------到这里为MSGs解析完成--------------------------------------------
                                if("QCParams".equals(qcList.item(ql).getNodeName())){
                                    Node QCParams = qcList.item(ql);
                                    NodeList QCParamsList = QCParams.getChildNodes();
                                    for(int qcpl=0;qcpl<QCParamsList.getLength();qcpl++){
                                        if("QCParam".equals(QCParamsList.item(qcpl).getNodeName())){
                                            Node param = QCParamsList.item(qcpl);
                                            QCItem.QCParam qq = new QCItem.QCParam();
                                            NamedNodeMap map = param.getAttributes();
                                            qq.Param = map.getNamedItem("Param").getNodeValue();
                                            qq.ValidMin = map.getNamedItem("ValidMin").getNodeValue();
                                            qq.ValidMax = map.getNamedItem("ValidMax").getNodeValue();
                                            qq.ValidAvg = map.getNamedItem("ValidAvg").getNodeValue();
                                            Log.i("QCParam",">>>>>>>>"+qq.Param+"<<<<<<<<<");
                                            qqList.add(qq);
                                        }
                                    }
                                }
                                //------------------到这里为QCParams解析完成--------------------------------------------
                                if("ENVParams".equals(qcList.item(ql).getNodeName())){
                                    Node QCParams = qcList.item(ql);
                                    NodeList QCParamsList = QCParams.getChildNodes();
                                    for(int qcpl=0;qcpl<QCParamsList.getLength();qcpl++){
                                        if("ENVParam".equals(QCParamsList.item(qcpl).getNodeName())){
                                            Node param = QCParamsList.item(qcpl);
                                            QCItem.ENVParam qq = new QCItem.ENVParam();
                                            NamedNodeMap map = param.getAttributes();
                                            qq.Param = map.getNamedItem("Param").getNodeValue();
                                            if(map.getNamedItem("ValidMin")!=null){
                                                qq.ValidMin = map.getNamedItem("ValidMin").getNodeValue();
                                            }
                                            if(map.getNamedItem("ValidMax")!=null){
                                                qq.ValidMax = map.getNamedItem("ValidMax").getNodeValue();
                                            }
                                            envList.add(qq);
                                        }
                                    }
                                }
                                //------------------到这里为ENVParams解析完成--------------------------------------------
                            }
                            mQCItem.setmMsgs(m);
                            mQCItem.setQCParams(qqList);
                            mQCItem.setENVParams(envList);
                            qciList.add(mQCItem);
                        }
                    }
                    Globals.device.setQCset(qciList);
                    Globals.QClist = qciList;
                    Log.i("QCParam",">>>>>!@#$%#!@#>>>"+Globals.device.getQCset().size()+"<<<<<<<");
                }
            /**
             * QCSET解析 ----------------------------------------------------------------
             */
            /**
             * REALTIME解析 ----------------------------------------------------------------
             */
            if("RealTimeSet".equals(nodeList.item(i).getNodeName())){
                Node realTimeSet = nodeList.item(i);
                NodeList reltimes = realTimeSet.getChildNodes();
                LinkedList<RealTimeSet> realList = new LinkedList<>();
                for(int r=0;r<reltimes.getLength();r++){
                    if("RealTimeParam".equals(reltimes.item(r).getNodeName())){
                        RealTimeSet real = new RealTimeSet();
                        NamedNodeMap mpr = reltimes.item(r).getAttributes();
                        Node rname = mpr.getNamedItem("Name");
                        real.name = rname.getNodeValue();
                        realList.add(real);
                    }
                }
                Globals.device.setRealTimeSet(realList);
            }


        }
    }
    class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return Globals.QClist.size();
        }

        @Override
        public Object getItem(int i) {
            return Globals.QClist.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            if (view == null) {
                view = View.inflate(getActivity(), R.layout.list_item_dataset, null);
            }
            TextView tv = (TextView) view.findViewById(R.id.pad_tv_data);
            if (Globals.QClist.size() == 0) {
                tv.setText("没有数据，请稍后。。。。");
            } else {
                tv.setText(Globals.QClist.get(i).toString());
            }
            return view;
        }
    }
}
